package cn.edu.cxcyzx.util;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import cn.edu.cxcyzx.entity.Gitee;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
/**
 * 使用Guava 的缓存包
 * @author zxl
 * @date   2018年6月23日下午8:18:12
 * @描述:
 *
 */
public class CatchUtil {
	
	//使用本地缓存，缓存满时使用LRU算法清缓存,缓存有效期12小时
	private static LoadingCache<String,Object> loadingCache=CacheBuilder.newBuilder()
			.initialCapacity(1000)
			.maximumSize(10000)
			.expireAfterAccess(1, TimeUnit.HOURS)
			.build(new CacheLoader<String,Object>(){
				//默认的数据加载实现，当调用get取值的时候，如果key没有对应的值，就调用这个方法
				@Override
				public Object load(String arg0) throws Exception {
					// TODO Auto-generated method stub
					System.out.println("arg0:"+arg0);
					return null;
				}
				
			});
	
	public static void setValue(String key,Object value){
        loadingCache.put(key, value);
    }

    public static Object getValue(String key){
    	if(loadingCache.size()==0){
    		return null;
    	}
    	System.out.println("loadingCache.size():"+loadingCache.size());
    	Object value=null;
    	try {
			value=loadingCache.get(key);
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return value;
    }
    
    public static long getSize(){
    	return loadingCache.size();
    }
    
    public  static void printf(){
    	Map<String,Object> m=loadingCache.asMap();
    	if(m.size()<=0){
    		return;
    	}
    	Set<String> set=m.keySet();
    	Iterator<String> iterator=set.iterator();
    	while (iterator.hasNext()) {
			String key = (String) iterator.next();
			try {
				System.out.println("key:"+key+";value:"+((Gitee)loadingCache.get(key)).toString());
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
    }
    
}
